package pe.com.csi.pm.regexiv.widget;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pe.com.csi.pm.regexiv.ValidatorProgresivas;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;

import android.text.TextWatcher;

import android.util.AttributeSet;

import android.widget.EditText;

public class MyEditText extends EditText implements TextWatcher {

	public MyEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.setKeyListener(new ValidatorProgresivas());
	}

	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setKeyListener(new ValidatorProgresivas());
	}

	public MyEditText(Context context) {
		super(context);
		this.setKeyListener(new ValidatorProgresivas());
	}

	public boolean isError() {
		boolean error = true;
		try {
			Pattern pattern = Pattern.compile("[0-9]{0,4}|[0-9]{1,4}[+][0-9]{3}");
			if (this.getText() == null || this.getText().toString().trim().length() <= 0) {
				error = false;
			} else {
				Matcher matcher = pattern.matcher(this.getText());
				if (!matcher.matches()) {
					error = true;
				} else {
					error = false;
				}
			}
		} catch (Exception e) {
			error = true;
			e.printStackTrace();
		}
		return error;
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		Pattern pattern = Pattern.compile("[0-9]{0,4}|[0-9]{1,4}[+][0-9]{3}");
		Matcher matcher = pattern.matcher(s);
		if (!matcher.matches()) {
			this.setTextColor(Color.RED);
			this.setError("0000+000");
		} else {
			this.setTextColor(Color.BLACK);
		}
	}
}
